#include "interface.h"

#include <QtGui\QGridLayout>
// 50 frames per second
const unsigned AnimationScroller::INTERVAL = (unsigned)(1000.0f / 50.0f);

AnimationScroller::AnimationScroller(QWidget* parent /* = NULL*/, unsigned _framesNumber /* = 0*/)
  : QWidget(parent)
  , framesNumber(_framesNumber)
  , m_mult(1)
{
  slider = new QSlider(Qt::Horizontal, this);
  slider->setMinimum(0);
  connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(moveToFrame(int)));

  timer = new QTimer(this);

  start = new QPushButton(this);
  start->setIcon(QIcon("Resources\\start_icon.png"));
  start->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

  connect(start, SIGNAL(clicked()), this, SLOT(animationStart()));
  connect(timer, SIGNAL(timeout()), this, SLOT(newFrame()));

  pause = new QPushButton(this);
  pause->setIcon(QIcon("Resources\\pause_icon.png"));
  pause->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
  connect (pause, SIGNAL(clicked()), this, SLOT(animationPause()));

  stop = new QPushButton(this);
  stop->setIcon(QIcon("Resources\\stop_icon.png"));
  stop->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
  connect (stop, SIGNAL(clicked()), this, SLOT(animationStop()));

  QGridLayout* pLayout = new QGridLayout(this);
  pLayout->addWidget(start, 0, 0, 1, 1);
  pLayout->addWidget(pause, 0, 1, 1, 1);
  pLayout->addWidget(stop, 0, 2, 1, 1);
  pLayout->addWidget(slider, 0, 3, 1, 3);
  setLayout(pLayout);
  setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
}


void AnimationScroller::setScale(const unsigned int n)
{
  slider->setMaximum(n);
  framesNumber = n;
}

void AnimationScroller::toStart()
{
  timer->stop();
  slider->setValue(0);
}

AnimationScroller::~AnimationScroller()
{
}
// SLOTS
void AnimationScroller::animationStart()
{
  timer->start(INTERVAL / m_mult);
  start->setEnabled(false);
  pause->setEnabled(true);
}
void AnimationScroller::animationStop()
{
  timer->stop();
  slider->setValue(0);
  start->setEnabled(true);
  pause->setEnabled(true);
}
void AnimationScroller::animationPause()
{
  timer->stop();
  start->setEnabled(true);
  pause->setEnabled(false);
}

void AnimationScroller::newFrame()
{
  if (slider->value() + (1 << m_mult) >= slider->maximum())
    slider->setValue(0);
  else
    slider->setValue(slider->value() + (1 << m_mult));
  emit animationAtFrame(slider->value());
}

void AnimationScroller::moveToFrame(int frameNumber)
{
  emit animationAtFrame(frameNumber);
}

void AnimationScroller::newAnimationSpeed(int mult)
{
  m_mult = mult;
  //timer->stop();
  //if (m_mult > INTERVAL)
  //  m_mult = INTERVAL;
  //timer->start(INTERVAL / m_mult);
  //timer->setInterval(INTERVAL / m_mult);
}



